package com.navinfo.tripanalysis.offline.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.navinfo.tripanalysis.common.util.JsonUtils;
import org.bson.Document;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

public class MongoUtils {
    /**
     * 对象转换成document
     *
     * @param obj   对象
     * @param clazz 对象所属类
     * @return document
     */
    public static Document buildDocument(Object obj, Class clazz) {
        Document document = new Document();
        if(obj != null) {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = null;
                try {
                    if (field.getType().isAssignableFrom(List.class) ||
                            field.getType().isAssignableFrom(Collection.class) ||
                            field.getType().isAssignableFrom(Map.class)) {
                        try {
                            value = JsonUtils.toJson(field.get(obj));
                        } catch (JsonProcessingException e) {
                            e.printStackTrace();
                        }
                    } else {
                        value = field.get(obj);
                    }
                } catch (IllegalAccessException e) {

                }

                if (value != null) {
                    document.append(field.getName(), value);
                }
            }
        }
        return document;
    }

    //获取表名后缀_周表
    public static String getWeekTableName(long date) {
        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        cal.setTime(new Date(date));
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        String monday = new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
        return monday;
    }

    //获取表名后缀_月表
    public static String getMonthTableName(long date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(date));
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        String day = new SimpleDateFormat("yyyyMM").format(calendar.getTime());
        return day;
    }

    public static void main(String[] args) {
        System.out.println( getMonthTableName(1538240400000l));
    }
}
